var io = require('socket.io').listen(3002);
var fs = require('fs');
var express = require('express');
var mysql = require('mysql');

var db = mysql.createConnection({
	host: 'localhost',
	user: 'jadesoft',
	password: '1212',
	database: 'jadesoft'
});

db.connect(function(err) {
	if(err) { console.log(err); }
});

var notes = [];
var isInitNotes = false;
var socketCount = 0;

io.sockets.on('connection', function (socket) {
	socketCount++;
	io.sockets.emit('Users Connected', socketCount);
	
	socket.on('disconnect', function() {
		socketCount--;
		io.socket.emit('Users Disconnected', socketCount);
	});
	
	socket.on('new note', function(data) {
		notes.push(data);
		io.sockets.emit('new note', data);
		db.query('INSERT INTO t_game(itemId, terms, flag) VALUES(?,?,?)', data.note);
	});
	
	if(!isInitNotes) {
		db.query('SELECT * FROM t_game')
			.on('result', function(data) {
				notes.push(data);
			})
			.on('end', function() {
				socket.emit('Initial Notes', notes);
			});
			
			isInitNotes = true;
	}
	else
	{
		socket.emit('Initial Notes', notes);
	}
});
